package logic

import (
	"context"
	"fmt"
	"meituan-waimai/models/cache"
	"meituan-waimai/models/mysql"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *meituanrpc.RegisterRequest) (*meituanrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	// 判断手机号是否被注册，防止重复注册
	mysql.DB.Where("mobile = ?", in.Mobile).First(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("手机号已被注册，请前往登录")
	}
	// 如果没有被注册，验证短信验证码是否正确
	smsCode := cache.RDB.Get(l.ctx, "SmsCode:"+in.Mobile).Val()
	if smsCode != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	user.Mobile = in.Mobile
	mysql.DB.Create(&user)
	return &meituanrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
